﻿using AutoMapper;
using B.S.Filtration.Domain;
using B.S.Filtration.Domain.专检;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Write.Api.Application.Command.AbnormalCommand;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Write.Api.Application.CommandHander.AbnormalHandler
{
    public class DelAbnormalHandler : IRequestHandler<DelAbnormalCommand, APIResult<int>>
    {

        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public DelAbnormalHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        public async Task<APIResult<int>> Handle(DelAbnormalCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var list = await db.Queryable<Abnormal>().FirstAsync(x => x.id == request.id);
            // 增加判空逻辑
            if (list == null)
            {
                result.code = APIResultCode.failed;
                result.msg = "未找到要删除的异常处理";
                return result;
            }

            list.IsDel = true;
            result.data = await db.Updateable<Abnormal>(list).ExecuteCommandAsync();
            if (result.data > 0)
            {
                result.code = APIResultCode.success;
                result.msg = "异常处理删除成功";
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = "异常处理删除失败";
            }
            return result;
        }
    }
}
